package com.xiaodou.mjf.application.core.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import com.xiaodou.mjf.application.core.repository.WithdrawalRepository;
import com.xiaodou.mjf.application.core.service.WithdrawalService;
import com.xiaodou.mjf.entity.core.Withdrawal;
import com.xiaodou.mjf.infrastructure.common.app.JpaSimpleService;

/***
 *
 * Withdrawal业务访问实现
 * 
 * @author XiaoDou.com Code Generator
 * @version 1.0 2014-10-29 17:37:52
 *
 */
@Service
@Transactional
public class WithdrawalServiceImpl extends JpaSimpleService<Withdrawal, String> implements WithdrawalService {

	Logger logger = LoggerFactory.getLogger(WithdrawalServiceImpl.class);

	@Resource
	WithdrawalRepository withdrawalRepository;

	@Override
	protected JpaRepository<Withdrawal, String> getRepository() {
		return withdrawalRepository;
	}

	@Override
	public Page<Withdrawal> page(Withdrawal entity) {
		return withdrawalRepository.findAll((root, query, cb) -> {
			Predicate p1 = cb.equal(root.get("status").as(Integer.class), entity.getStatus());
			Predicate p2 = cb.like(root.get("memberId").as(String.class), "%" + entity.getMemberId() + "%");

			SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
			String startStr = "2000-01-01";
			String endStr = "2300-01-01";
			Date startTime = entity.getStartTime();
			Date endTime = entity.getEndTime();
			try {
				if (startTime == null)
					startTime = spf.parse(startStr);
				if (endTime == null)
					endTime = spf.parse(endStr);

			} catch (Exception e) {
				logger.error(e.toString());
				e.printStackTrace();
			}
			Predicate p3 = cb.between(root.get("applyDate").as(Date.class), startTime, endTime);
			if (entity.getStatus().equals(-1)) {
				return query.where(p2, p3).getRestriction();
			}
			return query.where(p1, p2, p3).getRestriction();
		}, preparePage(entity, new Sort(new Sort.Order(Sort.Direction.ASC, "memberId"), new Sort.Order(Sort.Direction.DESC, "memberId"))));
	}

}
